<script setup lang="ts">
import type { FormRules, FormInstance } from 'element-plus'
import { User, Unlock } from '@element-plus/icons-vue'
import { isUsername, isPassword } from '@/utils/validate'
import { useAuthStore } from '@/store/auth'
import { useRouter, useRoute } from 'vue-router'
import { notify } from '@/utils/element'

/**
 * 路由
 */
const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

/**
 * 初始参数
 */
const state = reactive({
  isRemember: true,
  loading: false,
  loginData: {
    username: authStore.rememberData?.username,
    password: authStore.rememberData?.password,
  } as LoginData
})

/**
 * 表单规则
 */
const rules = reactive<FormRules>({
  username: [{ required: true, asyncValidator: checkUserName, trigger: 'blur' }],
  password: [{ required: true, asyncValidator: checkPassword, trigger: 'blur' }]
})

/**
 * 校验账号
 * @param _rule 
 * @param value 
 * @param callback 
 */
async function checkUserName(_rule: any, value: string, callback: Function) {
  if (!value) return callback(new Error('请输入有效账号/手机号！'))
  if (!isUsername(value)) callback(new Error('输入的格式不正确，请重新输入6-30位数字、字母和下划线！'))
  callback()
}

/**
 * 校验密码
 * @param _rule 
 * @param value 
 * @param callback 
 */
async function checkPassword(_rule: any, value: string, callback: Function) {
  if (!value) return callback(new Error('请输入有效密码！'))
  if (!isPassword(value)) callback(new Error('输入的格式不正确，请重新输入字母+数字+特殊字符，长度在6-30之间！'))
  callback()
}

const { isRemember, loading, loginData } = { ...toRefs(state) }

/**
 * 重置密码
 */
const resetPwd = () => {
  // console.log('重置密码', route.query?.redirect);
  router.replace({ path: '/resetPassword' })
}

/**
 * 提交数据
 */
const formRef = ref<FormInstance>()
function submitForm() {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    try {
      //登陆中
      loading.value = true
      //记住密码
      authStore.setRememberPwd(state.isRemember ? state.loginData : undefined)
      // 发送登录请求
      const res: any = await authStore.userLogin(state.loginData)
      // console.log('发送登录请求', res);
      // 跳转到来源地址 login?redirect=/home
      // console.log('route.query', route.query);
      router.replace({ path: <string>route.query?.redirect || '/' })
      notify(res.message, { type: 'success', duration: 2000 });
    } catch (error) {
    } finally {
      loading.value = false
    }
  })
}
</script>

<template>
  <div class="login-container">
    <div class="login-wrap">
      <img class="login-logo" src="@/assets/logo.png"></img>
      <div class="login-title">账号登录</div>
      <el-form ref="formRef" class="login-form" :model="loginData" size="large" :rules="rules">
        <el-form-item prop="username">
          <el-input v-model="loginData.username" placeholder="请输入账号/手机号" maxlength="30" :prefix-icon="User"
            clearable></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginData.password" type="password" placeholder="请输入密码" maxlength="30"
            :prefix-icon="Unlock" clearable show-password></el-input>
        </el-form-item>
        <el-form-item>
          <div class="login-other">
            <el-checkbox label="记住密码" v-model="isRemember"></el-checkbox>
            <span class="forget-pasword" @click="resetPwd">忘记密码?</span>
          </div>
          <el-button class="login-submit" type="primary" :loading="loading" @click="submitForm">
            {{ loading ? '正在登录...' : '登 录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
.login-container {
  height: 100%;
  width: 100%;
  background-image: url('@/assets/images/login-bj.png');
  background-size: cover;
  overflow: hidden;
  display: flex;
  align-items: center;

  // justify-content: center;
  .login-wrap {
    width: 410px;
    height: 460px;
    background-color: #fff;
    padding: 30px;
    margin: auto;
    margin-right: 130px;
    box-shadow: #74747462 0 2px 15px;
    border-radius: 10px;

    .login-logo {
      max-width: 130px;
      margin: auto;
      display: flex;
    }

    .login-title {
      font-size: 20px;
      height: 70px;
      line-height: 70px;
      font-weight: 500;
      text-align: left;
      color: #0d1234;
      letter-spacing: 2px;
    }

    .login-form {
      .el-form-item {
        margin-bottom: 27px;
      }

      .login-other {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 3px;

        .forget-pasword:hover {
          cursor: pointer;
          color: #285e7e;
        }

        span {
          font-size: 13px;
          font-weight: 500;
          color: #999;
        }
      }

      .login-submit {
        width: 100%;
        height: 40px;
        letter-spacing: 3px;
        font-weight: 500;
      }
    }
  }

}
</style>